/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2022-03-05 15:18:07
 * @LastEditors: ding-cx
 * @LastEditTime: 2022-03-28 15:09:55
 * @Description: file content
 */
import { Controller, IResponseBodyData } from "egg";

export default class DineggController extends Controller {
	constructor(ctx) {
		super(ctx);
	}

	/**
	 *
	 * @param {*} data 要发送给response的内容。
	 * @param {number} [status=20000] 自定义的状态码
	 * @param {string} [msg=""] 修改状态对应的msg信息。
	 */
	send(data: any, status = 20000, msg = "", errDetails?: string[]) {
		this.ctx.status = 200;
		const res: IResponseBodyData = {
			code: status,
			data,
			msg: msg,
			details: errDetails,
		};
		return res;
	}

	/**
	 *发送成功的响应，携带数据
	 *
	 * @param {*} data
	 */
	success(data) {
		return this.send(data, 20000, "success");
	}

	/**
	 *发送警告的响应，主体响应仍然是成功的，但是将携带一个弃用或变更之类的警告，提醒caller，该api将发生变化
	 *
	 * @param {*} data
	 */
	warning(data, msg?: string) {
		return this.send(data, 20000, "warning: this response will change: " + msg || "");
	}

	/**
	 *发送失败的响应，携带msg信息
	 *
	 * @param {*} msg
	 */
	error(msg, code: number = 50000, details?: string[]) {
		const res = this.send(null, code, msg);
		res.details = details;
		return res;
	}

	/**
	 * 响应http status 为400的错误，对浏览器端更友好
	 */
	errorBy400(msg, code = 50000, details?: string[]) {
		const res = this.error(msg, code, details);
		this.ctx.status = 400;
		return res;
	}
}
